const fs = require("fs");

const { distDir, rootPath } = require("../config/app.config");

function handleScripts() {
  const url = rootPath(distDir, "index.html");

  // 读取disDir/index.html
  let htmlStr = fs.readFileSync(url, { encoding: "utf-8" });

  // 匹配script标签
  const reg = /<script.*>/g;

  /*
   * 替换关键字
   * <script type="module" crossorigin src="./assets/index.js"></script>
   * <script defer src="./assets/index.js"></script>
   */
  htmlStr = htmlStr.replace(reg, (str) => {
    //
    return str
      .replace(/\snomodule|\scrossorigin|\stype="module"/g, "")
      .replace("<script", "<script defer");
  });

  // 输出文件
  fs.writeFileSync(url, htmlStr);
}

function handleLinks() {
  const url = rootPath(distDir, "index.html");

  // 读取disDir/index.html
  let htmlStr = fs.readFileSync(url, { encoding: "utf-8" });

  // 匹配link标签
  const reg = /<link.*>/g;

  htmlStr = htmlStr.replace(reg, (str) => {
    // 替换关键字
    return str.replace(/\snomodule|\scrossorigin|\stype="module"/g, "");
  });

  // 输出文件
  fs.writeFileSync(url, htmlStr);
}

handleScripts();
handleLinks();

